package com.estronger.shopmanage.fragment.send.pg;

import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.estronger.pull_to_refresh_expandablelist.CommonFooterView.State;
import com.estronger.pull_to_refresh_expandablelist.PullToRefreshBase;
import com.estronger.pull_to_refresh_expandablelist.PullToRefreshBase.OnRefreshListener;
import com.estronger.pull_to_refresh_expandablelist.PullToRefreshListView;
import com.estronger.shopmanage.R;
import com.estronger.shopmanage.adapter.tasking.DeliverDPGListAdapter;
import com.estronger.shopmanage.adapter.tasking.DeliverYPGListAdapter;
import com.estronger.shopmanage.base.MyApplication;
import com.estronger.shopmanage.bean.DeliverDPG;
import com.estronger.shopmanage.bean.DeliverYPG;
import com.estronger.shopmanage.manager.NetManager;
import com.estronger.shopmanage.ui.send.pg.DeliverPGActivity;
import com.estronger.shopmanage.utils.NetUtils;
import com.estronger.shopmanage.utils.Toast;
import com.estronger.shopmanage.view.CircularProgress;
import com.google.gson.Gson;
import com.lidroid.xutils.http.RequestParams;

import cn.jesse.nativelogger.NLogger;

/**
 * 送货的五个Fregment的公共父类
 *
 * @author Administrator
 */
public abstract class DeliverPGBaseFragment extends Fragment implements
        OnRefreshListener<ListView> {//
    protected PullToRefreshListView mListView;
    protected RequestParams params;
    protected RelativeLayout root;
    protected CircularProgress bar;
    protected TextView empty_view;
    protected DeliverDPGListAdapter adapterdp;
    protected DeliverYPGListAdapter adapteryp;
    private DeliverDPG data;
    private DeliverDPG tmpdata;
    private DeliverYPG data2;
    private DeliverYPG tmpdata2;
    Gson gson = new Gson();
    private DeliverPGActivity activity;
    public String type = "";
    private int pageindex = 1;
    private String pagesize = "10";
    boolean isFrist = false;

    protected NetManager netManager = new NetManager() {
        @Override
        public void onNetWorkErorr(int code, String result) {
            try {
               if (null != mListView) {
                    mListView.setState(State.HIDE);
                    if (null != bar)
                        bar.setVisibility(View.GONE);
                    mListView.onRefreshComplete();
                    if (data != null) {
                        if (data.data.list.size() == 0) {
                            empty_view.setVisibility(View.VISIBLE);
                        }
                    } else {
                        empty_view.setVisibility(View.VISIBLE);
                    }
                }
            } catch (Exception e) {
                NLogger.e("" + e.getMessage());
            }
        }

        @Override
        public void onNetWorkSuccess(int code, String result) {
            if (null != bar)
                bar.setVisibility(View.GONE);
            if (null != mListView) {
                mListView.setState(State.HIDE);
                mListView.onRefreshComplete();
                if (code == NetManager.DELIVER_PG) {
                    reflashdata(gettype(), result);
                }
            }
        }
    };


    public void connect(final String gettype,boolean isFrist) {
        this.isFrist = isFrist;
        if(isFrist){
            data = null;
            data2 = null;
            pageindex = 1;
        }
        if(activity==null){
            activity = (DeliverPGActivity) getActivity();
        }else {
            activity.getTitleNum();
        }
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                RequestParams params = new RequestParams();
                params.addBodyParameter("usercode", MyApplication.getUserCode());
                params.addBodyParameter("gettype", gettype);
                params.addBodyParameter("pagesize", pagesize);
                params.addBodyParameter("pageindex", String.valueOf(pageindex));
                params.addBodyParameter("sf_action", "getdlvassignlist");
                netManager.connectWork(params, NetManager.DELIVER_PG);
            }
        }, 1000);
    }

    private void reflashdata(String gettype, String result) {
        type = gettype;
        if (null != bar) bar.setVisibility(View.GONE);
        if (null != mListView) {
            mListView.setState(State.HIDE);
            mListView.onRefreshComplete();
        }
        if (type.equals("0")) {
            //getDPG();
            tmpdata = gson.fromJson(result, DeliverDPG.class);
            if(data == null || data.data.list.size() == 0){
                adapterdp = new DeliverDPGListAdapter(activity, tmpdata.data.list);
                data = tmpdata;

                if(tmpdata.data.list.size() >= Integer.parseInt(pagesize)){
                    mListView.setMode(PullToRefreshBase.Mode.BOTH);
                }
            }else if(data.data.list.size()>0){
                if(tmpdata.data.pageindex == data.data.pageindex){
                    return;
                }
                for(int i=0;i<tmpdata.data.list.size();i++){
                   data.data.list.add(tmpdata.data.list.get(i));
                }
                if(tmpdata.data.list.size() == 0){
                    Toast.show(activity,"没有更多了！",2000);
                }
                adapterdp = new DeliverDPGListAdapter(activity, data.data.list);
                //延时一会，然后自动定位到最后一条记录(必须要重新定位，不要删除)
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        mListView.setSelection((pageindex-1)*Integer.parseInt(pagesize));
                    }
                },500);
            }

            mListView.setAdapter(adapterdp);
            adapterdp.notifyDataSetChanged();
            if (data.data.list.size() > 0
                    && empty_view.getVisibility() == View.VISIBLE) {
                empty_view.setVisibility(View.GONE);
            }
            if (data.data.list.size() == 0) {
                empty_view.setVisibility(View.VISIBLE);
            }
        } else {
            //getYPG();
            tmpdata2 = gson.fromJson(result, DeliverYPG.class);
            if(data2 == null || data2.data.list.size() == 0){
                adapteryp = new DeliverYPGListAdapter(activity, tmpdata2.data.list);
                data2 = tmpdata2;

                if(tmpdata2.data.list.size() >= Integer.parseInt(pagesize)){
                    mListView.setMode(PullToRefreshBase.Mode.BOTH);
                }
            }else if(data2.data.list.size()>0){
                if(tmpdata2.data.pageindex == data2.data.pageindex){
                    return;
                }
                for(int i=0;i<tmpdata2.data.list.size();i++){
                    data2.data.list.add(tmpdata2.data.list.get(i));
                }
                if(tmpdata2.data.list.size() == 0){
                    Toast.show(activity,"没有更多了！",2000);
                }
                adapteryp = new DeliverYPGListAdapter(activity, data2.data.list);
                //延时一会，然后自动定位到最后一条记录(必须要重新定位，不要删除)
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                         mListView.setSelection((pageindex-1)*Integer.parseInt(pagesize));
                    }
                },500);
            }

            mListView.setAdapter(adapteryp);
            adapteryp.notifyDataSetChanged();
            if (data2.data.list.size() > 0
                    && empty_view.getVisibility() == View.VISIBLE) {
                empty_view.setVisibility(View.GONE);
            }
            if (data2.data.list.size() == 0) {
                empty_view.setVisibility(View.VISIBLE);
            }
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        activity = (DeliverPGActivity) getActivity();
        root = (RelativeLayout) View.inflate(activity,
                R.layout.fragment_history, null);
        mListView = (PullToRefreshListView) root
                .findViewById(R.id.success_listview);

        bar = (CircularProgress) root.findViewById(R.id.loding_view);
        empty_view = (TextView) root.findViewById(R.id.empty_view);
        mListView.setOnRefreshListener(this);
        //mListView.setMode(Mode.BOTH);
        mListView.setState(State.HIDE);

        return root;
    }

    protected abstract boolean needConnect();

    protected abstract String gettype();

    protected void loadData() {
        if (!NetUtils.isNetworkConnected(getActivity())) {
            mListView.postDelayed(new Runnable() {
                @Override
                public void run() {
                    mListView.onRefreshComplete();
                    Toast.show(activity, "当前无网络链接！", 2000);
                }
            }, 1000);
        } else {
            connect(gettype(),false);
        }
    }

    @Override
    public void onRefresh(PullToRefreshBase<ListView> refreshView) {
        if (mListView.isHeaderShown()) {
            pageindex = 1;
            data = null;
            data2 = null;
            loadData();
        } else if(mListView.isFooterShown()) {
            pageindex+=1;
            loadData();
        }
        mListView.postDelayed(new Runnable() {
            @Override
            public void run() {
                mListView.onRefreshComplete();
            }
        }, 1000);
    }

}
